package data_structure.video;

class CircleArrayQueueDemo {
    public static void main(String[] args) {
        CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);
        circleArrayQueue.addQueue(1);
        circleArrayQueue.addQueue(2);
        circleArrayQueue.addQueue(3);
        circleArrayQueue.addQueue(4);
        System.out.println("===遍历===");
        circleArrayQueue.showQueue();
        System.out.println("===取数据===");
        System.out.println(circleArrayQueue.getQueue());
        System.out.println(circleArrayQueue.getQueue());
        System.out.println(circleArrayQueue.getQueue());
        circleArrayQueue.showQueue();
        circleArrayQueue.addQueue(11);
        circleArrayQueue.addQueue(22);
        circleArrayQueue.showQueue();
    }
}

class CircleArrayQueue{
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;

    //添加数据
    public void addQueue(int n){
        if (isFull()) {
            System.out.println("队列已经满了");
            return;
        }
        arr[rear] = n;
        rear = (rear+1) % maxSize;
    }

    //遍历数据
    public void showQueue(){
        if (isEmpty()){
            System.out.println("队列为空...");
            return;
        }
        for (int i = front; i < front + size(); i++) {
            System.out.print(arr[i%maxSize] + " ");
        }
        System.out.println();
    }

    //求出房前队列有效数据个数
    public int size(){
        return (rear - front + maxSize)%maxSize;
    }

    //取出数据
    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空无法取出数据...");
        }
        //1.先将 front 对应的值 保留到一个临时变量
        //2.将 front 后移
        //3.将临时保存的变量返回
        int value = arr[front];
        front = (front+1) % maxSize;
        return value;
    }

    //数组初始化
    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return rear == front;
    }

    //判断队列是否满
    public boolean isFull(){
        return (rear+1)%maxSize == front;
    }
}
